import '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'
import http from '@/utils/request'
import {userApi} from "@/api/user";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    nav:''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_NAV:(state, nav)=>{
    state.nav = nav
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    // const { username, password } = userInfo

    return new Promise((resolve, reject) => {
      userApi.login(userInfo)
        .then(response => {
          commit('SET_TOKEN', response.token)
          setToken(response.token)
          resolve()
        }).catch(error => {
        reject(error)
      })
    })

  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      userApi.getLoginUserInfo()
        .then(response => {
          const {data} = response

          if (!data) {

            return reject('未知错误，请联系管理员')
          }
          //TODO 解耦后改回
          const {teacher,student} = data;
          // const {teacher,student} = {teacher:"demo"};
          if(teacher){
            commit('SET_NAME', teacher.name)
          }else if(student){
            commit('SET_NAME', student.name)
          }
          // }else{
          //   return reject('未找到对应角色，请联系管理员')
          // }
          // const {name, avatar} = data
          //
          // commit('SET_NAME', name)
          // commit('SET_AVATAR', avatar)
          resolve(response)
        }).catch(err=>{
          reject(err)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      userApi.logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')

      }).catch(error => {

      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

